package org.fmi.lje.model.util;

import java.io.File;
import java.io.FileReader;
import java.io.Writer;
import java.net.URL;

import org.apache.log4j.Logger;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.fmi.lje.model.UmlGenProject;
import org.xml.sax.InputSource;

public class ProjectUtil {

	private static final Mapping mapping = new Mapping();;
	private static final Logger log = Logger.getLogger(ProjectUtil.class);

	static {
		try {
			URL mappingStream = Thread.currentThread().getContextClassLoader().getResource("uml-gen-project-mapping.xml");
			mapping.loadMapping(mappingStream);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	protected static UmlGenProject loadProject(File target) {
		try {
			Unmarshaller unmarshaller = new Unmarshaller();
			unmarshaller.setMapping(mapping);

			return (UmlGenProject) unmarshaller.unmarshal(new InputSource(new FileReader(target)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	protected static void saveProject(Writer writer, UmlGenProject project) {
		try {
			Marshaller marshaller = new Marshaller();
			marshaller.setMapping(mapping);
			marshaller.setWriter(writer);
			marshaller.setSuppressXSIType(true);

			marshaller.marshal(project);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			
			throw new RuntimeException(e.getMessage(), e);
		}
	}
	
	public static UmlGenProject loadProjectFromFolder(File folder) {
		if(folder.isDirectory()) {
			File[] files = folder.listFiles();
			
			for(File file : files) {
				if(file.getName().endsWith(".umlg.xml")) {
					UmlGenProject project = loadProject(file);
					
					if(project.getProjectFolder() == null) {
						project.setProjectFolder(folder.getAbsolutePath());
					}
					
					return project;
				}
			}
		}
		
		throw new RuntimeException("Project folder is not a recognised project type!");
	}
}
